-- lua/plugins/nerdtree.lua

-- 设置 Nerdtree 打开/关闭的快捷键
vim.keymap.set("n", "<leader>t", ":NERDTreeToggle<CR>", { silent = true })

-- tab 和 shift-tab 在 nerdtree 或 buffer 中切换
vim.api.nvim_exec([[
function! SmartBufferSwitch(next)
    if &filetype ==# 'nerdtree'
        wincmd l
    elseif &filetype ==# 'startify'
        echo "No buffer to switch."
    else
        if a:next
            bnext!
        else
            bprevious!
        endif
    endif
endfunction
]], false)

vim.keymap.set("n", "<Tab>", ":call SmartBufferSwitch(1)<CR>", { silent = true })
vim.keymap.set("n", "<S-Tab>", ":call SmartBufferSwitch(0)<CR>", { silent = true })

-- 关闭缓冲区并自动跳转/新建
vim.api.nvim_exec([[
function! CloseBuffer()
    if exists('t:NERDTreeBufName') && bufname('%') != t:NERDTreeBufName
        let l:non_nerd_buffers = len(filter(range(1, bufnr('$')), 'buflisted(v:val) && bufname(v:val) != t:NERDTreeBufName'))
        if l:non_nerd_buffers > 1
            bp | bd #
        else
            bd
            Startify
        endif
    else
        let l:buffers = len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
        if l:buffers > 1
            bp | bd #
        else
            bd
            Startify
        endif
    endif
endfunction
]], false)

vim.keymap.set("n", "<leader>d", ":call CloseBuffer()<CR>", { silent = true })

-- Nerdtree 选项设置
vim.g.NERDSpaceDelims = 1
vim.g.NERDCompactSexyComs = 1
vim.g.NERDTreeIgnore = { [[\.pyc]], [[\~$]], [[\.swp]] }
vim.g.NERDTreeFileExtensionHighlightFullName = 1
vim.g.NERDTreeExactMatchHighlightFullName = 1
vim.g.NERDTreePatternMatchHighlightFullName = 1

return {}
